/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.webapp.remoting;

import lombok.Cleanup;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jrose.core.util.XMLUtils;
import org.springframework.core.io.Resource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

@RequiredArgsConstructor
public class ExposedServiceConfigParser {
    @NonNull private final Resource resource;
    @NonNull private final ClassLoader classLoader;

    public List<ExposedServiceConfig> parse() {
        try {
            @Cleanup InputStream inputStream = resource.getInputStream();
            Document document = XMLUtils.getDocumentBuilder().parse(inputStream);
            Element root = document.getDocumentElement();
            return doParse(root);
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }

    private List<ExposedServiceConfig> doParse(Element root) throws Exception {
        List<ExposedServiceConfig> services = new LinkedList<>();
        List<Element> serviceElements = XMLUtils.getChildElements(root, "service");
        for (Element serviceElement : serviceElements) {
            Class<?> serviceInterface = classLoader.loadClass(serviceElement.getAttribute("serviceInterface"));
            String beanName = serviceElement.getAttribute("beanName");
            String remoteUrl;
            if (serviceElement.hasAttribute("remoteUrl")) {
                remoteUrl = serviceElement.getAttribute("remoteUrl");
            } else {
                remoteUrl = "/" + beanName;
            }
            if (!StringUtils.startsWith(remoteUrl, "/")) {
                remoteUrl = "/" + remoteUrl;
            }

            ExposedServiceConfig config = new ExposedServiceConfig();
            config.setServiceInterface(serviceInterface);
            config.setBeanName(beanName);
            config.setRemoteUrl(remoteUrl);
            services.add(config);
        }
        return services;
    }
}
